<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2021/8/18
 * Time: 4:49 下午
 */

namespace App\Models\CacheModel\live;

use app\chat\LiveMessage;
use App\Models\CacheModel\AppConfig;
use App\Models\CacheModel\Goods;
use App\Models\CacheModel\MallGoodsAttr;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use App\Models\Api\BaseCache;
use think\Cache;
use think\Db;
use think\Env;
use think\Exception;
use think\Log;
use AstroTool\Cache\CacheManage;

/**
 * Class LiveRecordingInfo
 * @package App\Models\CacheModel\live
 */
class LiveRecordingInfo extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.live_recording_info';

    protected $cacheModel = 'live.live_recording';

    protected $cacheIdKey = 'id';

    /**
     * 获取直播间信息
     * @param $live_id
     * @param int $uid
     * @param int $is_h5
     * @return array
     * @throws ApiException
     */
    public function getLiveInfo($live_id, $is_h5 = 0, $uid = 0, $isManage = false)
    {
        $anchor = (new LiveAnchorInfo())->getInfoById($live_id);
        //获取直播间最新的直播记录
//        $recordId = (new LiveRecordingInfo())->getNewestRecord($live_id);
        $recordId = input('live_record_id/d', 0);
        $recordIdIsGetNew = false;
        if (!$recordId)
        {
            $recordId = (new LiveRecordingInfo())->getNewestRecord($live_id);
            $recordIdIsGetNew = true;
        }
//        (new LiveRecordingInfo())->checkRecordId($live_id, $recordId);
        $record = $this->getInfoById($recordId);
        if ($recordIdIsGetNew && $record && (int)$record['status'] !== 1)
        {   // 如果直播记录ID是获取的最新的直播记录ID 但是直播记录的开播状态是未开播 则吧直播记录ID信息还原
            $record = null;
            $recordId = 0;
        }

        if (!$recordIdIsGetNew && (int)$record['live_id'] !== $live_id)
        {   // 如果传过来的直播间记录ID 不是当前直播的记录ID   则获取最新的直播记录信息
            $recordId = (new LiveRecordingInfo())->getNewestRecord($live_id);
            $record = $this->getInfoById($recordId);
        }

        $live_id = $record['live_id'] ?? $live_id;
//        if (!$record && !$is_h5)
//        {
//            throw new ApiException('直播不存在');
//        }
        $liveUrl = isset($record['pull_url']) ? json_decode($record['pull_url'], true) : '';
        if ($is_h5)
        {
            $liveUrl = $liveUrl['udp_h5_url'] ?? '';
        } else
        {
            $liveUrl = $liveUrl['udp_app_url'] ?? '';
        }

        $pull_url_definition_list = [];//清晰度列表
        try
        {
            if ((int)$record['status'] === 1)
            {
                $config = (new AppConfig())->configInfo('live');
                $live_definition_list_conf = json_decode(htmlspecialchars_decode($config['live_definition_list']), true);
                if (empty($live_definition_list_conf) || !is_array($live_definition_list_conf))
                {
                    Log::write("AppConf配置的live_definition_list参数异常！", 'error', true);
                } else
                {
                    $pull_url_definition_list_db = isset($record['pull_url_definition_list']) ? json_decode($record['pull_url_definition_list'], true) : '';
                    if (count($live_definition_list_conf) === count($pull_url_definition_list_db))
                    {
                        if ($is_h5)
                        {//todo h5暂时播放LD，实际看效果
                            $liveUrl = $pull_url_definition_list_db[2]['udp_h5_url'];
                        }

                        //h5和app都返回多分辨率的播放列表
                        foreach ($live_definition_list_conf as $k => $v)
                        {
                            $pull_url_definition_list[] = [
                                'title' => $v['title'],
                                'url' => $pull_url_definition_list_db[$k]['udp_app_url'],
                                'hls' => $pull_url_definition_list_db[$k]['hls'],
                            ];
                        }
                    } else
                    {
                        Log::write("数据库里的清晰度和App配置里的清晰度数量不一致！[live_definition_list_conf=" . json_encode($live_definition_list_conf) . ",pull_url_definition_list=" . json_encode($pull_url_definition_list) . "]", 'error', true);
                    }
                }

            }
        }
        catch (\Exception $e)
        {
            Log::write("获取多个清晰度的播流地址异常：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
        }

        $config = (new AppConfig())->configInfo('live');

        //公告信息检查
        if (!isset($config['live_notice'], $config['live_notice_color']))
        {
            Log::write('直播公告消息未设置，请在后台-》App配置里进行配置，live_notice 和 live_notice_color', 'error', true);
            $config['live_notice_color'] = '';
            $config['live_notice'] = '';
        }
        // 获取主播 麦克风和摄像头开启状态
        $cameraRadioStatus = Cache::get('live:camera_radio_status' . $live_id);
        // 获取直播间 推荐商品信息
        $recommendGood = null;
        $recommendGoodIdInfo = Cache::get('live_recommend_goods_' . $recordId, false);
        if ($recommendGoodIdInfo)
        {// 当前存在推荐商品
            [$category, $recommendGoodId] = explode('-', $recommendGoodIdInfo);
            $liveGoodsModel = new LiveGoodsActivity();
            $goodInfo = $liveGoodsModel->getInfoById((int)$recommendGoodId);
            $explode = explode(',', $goodInfo['gids']);
            sort($explode);
            $gid = current($explode);
            if ($goodInfo['category'] == 2)
            {
                $tmp = (new MallGoodsAttr())->batGetInfo([$gid], ['now_price']);
                $orPrice = sprintf('%.2f', current($tmp)['now_price']);
                $nowPrice = sprintf('%.2f', $goodInfo['attr']);
                $btnTxt = '立即购买';
            } else
            {
                if ($goodInfo['attr'] != 1)
                {
                    $discount = (new Util())->numberChinese($goodInfo['attr'] * 10);
                    $btnTxt = "特惠{$discount}折";
                } else
                {
                    $btnTxt = '立即购买';
                }
            }

            (new Goods())->goodsTargetLink((int)$goodInfo['gtype'], $goodInfo['link']);

            $recommendGood = [
                'id' => $recommendGoodId,
                'title' => $goodInfo['name'],
                'img' => $goodInfo['img'],
                'name' => $goodInfo['des'],
                'original_price_des' => $orPrice ?? '',
                'now_price' => $nowPrice ?? '',
                'btn_info' => [
                    'name' => $btnTxt,
                    'target' => $goodInfo['target'],
                    'link' => $goodInfo['link'] . '&is_jump_intro=1&live_id=' . $live_id . '&live_record_id=' . $recordId
                ]
            ];
        }
        $hotData = (new LiveStatusDataRecord())->getHotNumData($live_id);
        //获取直播预告信息
        $preview = (new LiveBroadcastPreview())->getNewestPreview();

        //增加基数
        $baseInfo = Cache::get($live_id . '-live_people_num-' . $recordId);
        if ($baseInfo)
        {
            $baseInfo = json_decode($baseInfo, true);
            if ($baseInfo['type'] == 1)
            {
                $time = time();
                $timeEx = $time - $baseInfo['timestamp'];
                $duration = $baseInfo['duration'] * 60;
                if ($timeEx >= $duration)
                {
                    $hotData['online_hot'] += $baseInfo['num'] + ($baseInfo['start_base_num'] ?? 0);
                    $hotData['total_hot'] += $baseInfo['num'] + ($baseInfo['start_base_num'] ?? 0);
                } else
                {
                    $num = (int)(($timeEx / $duration) * $baseInfo['num']) + ($baseInfo['start_base_num'] ?? 0);
                    $hotData['online_hot'] += $num;
                    $hotData['total_hot'] += $num;
                }
            } else
            {
                $hotData['total_hot'] += (($hotData['online_hot'] * $baseInfo['num']) - $hotData['online_hot']);
                $hotData['online_hot'] *= $baseInfo['num'];
            }
        }
        $sendMsgRecord = CacheManage::getInstance()->redisHandler->lRange('live:send:msg:record:' . $live_id, 0, -1);
        $sendMsgHistoryList = [];
        if (!empty($sendMsgRecord))
        {
            for ($i = count($sendMsgRecord) - 1; $i >= 0; $i--)
            {
                $sendMsgHistoryList[] = json_decode($sendMsgRecord[$i], true);
            }
        }
        // 暂时主播端只有ios
        $shareImg = request()->header('app-type') === 'android' && Util::CheckAppVersion('2.7.2') !== '小' ? 'live' : (Env::get('host.photo') . 'live_share_logo.png');

        //直播中
        $data = [
            'id' => (int)($record['id'] ?? 0),
            'avatar' => $anchor['avatar'],
            'nickname' => $anchor['name'],
            'online_num' => (int)$hotData['online_hot'],
            'hot_num' => (int)$hotData['total_hot'],
            'get_data_url' => $liveUrl,
            'pull_url_definition_list' => $pull_url_definition_list,
            'camera_status' => $cameraRadioStatus['camera_status'] ?? 1,
            'microphone_status' => $cameraRadioStatus['radio_status'] ?? 1,
            'live_status' => Cache::get('live:live_status:' . $live_id . ':' . ($record['id'] ?? 0), 1),
            'rtc_config' => (new LiveAnchorInfo())->getRtcConfig($live_id),
            'msg_info' => [
                'color' => $config['live_notice_color'],
                'content' => $config['live_notice'],
            ],
            'award_active' => (new LiveAwardAcitveRecord())->getHomeNewAwardAcitveInfo($live_id),
            'coupon_active' => (new LiveCouponActiveRecord())->getHomeNewCouponAcitveInfo($live_id),          // 获取直播间 抢优惠券活动
            'recommend_good' => $recommendGood,
            'List_rules' => (new LiveAnchorInfo())->getListRules(),
            'gift_rules' => (new LiveAnchorInfo())->getGiftRules(),
            // 'lottie_file_list' => (new LiveGift())->getLottieFile(),
            'live_content' => $preview['broadcast_content'] ?? '',
            'live_start_time_info' => isset($preview['live_start_time']) ? date('n月d日 H:i', $preview['live_start_time']) : '',
            'send_msg_record' => $sendMsgHistoryList,
            'share_info' => [
                'title' => $anchor['name'] . '正在直播',
                'desc' => $anchor['name'] . '正在进行精彩直播，直播间会有大量福利放送，快去和主播互动吧！',
                'url' => Env::get('host.domain') . '/web/live/index.html?live_id=' . $live_id . '&live_record_id=' . $recordId,
                'img' => $shareImg,
            ],
            'foresee_url' => Env::get('host.domain') . '/web/live/index?live_id=' . $live_id,
            'pop_msg_rtc' => null,
            'rtc_status' => 0
        ];
        //判断直播是否已开启
        if (!$record)
        {
            $data['status'] = 0;
        } elseif ((int)$record['status'] === 1)
        {   // 直播中
            $data['status'] = 1;
            $rtcRecordModel = new LiveRtcRecord();
            $nowRtcData = $rtcRecordModel->getNowRtcDataByCache($data['id']);
            if ($isManage)
            {
                $rtcSwitch = (int)(Cache::get("live:rtc_switch:{$live_id}:{$data['id']}", 0));
                if ($nowRtcData)
                {   // 连麦状态 带...
                    $nowRtcData['status'] = (int)$nowRtcData['status'];
                    $popMsgRtc = [
                        'type' => 1,
                        'toast' => '',
                        'user_info' => [
                            'name' => $nowRtcData['nickname'],
                            'avatar' => $nowRtcData['avatar'],
                            'uen' => $nowRtcData['uen'],
                            'status' => 0,
                            'des_network' => '',
                        ],
                        'btn_list' => []
                    ];
                    if ($nowRtcData['status'] === 1)
                    {   // 等待接听中
                        $popMsgRtc['btn_list'] = [
                            [
                                'type' => 1,
                                'title' => '取消连麦',
                                'target' => 'api',
                                'link' => '/live/v2/live/request_rtc_interaction?action=4&need_auth=2',
                                'mic_auth_deny' => null,
                                'action' => 4,
                            ], [
                                'type' => 2,
                                'title' => '等待接听中…',
                                'target' => '',
                                'link' => '',
                                'mic_auth_deny' => null,
                                'action' => 0,
                            ]
                        ];
                    } elseif ($nowRtcData['status'] === 2)
                    {   // 连接中
                        $popMsgRtc['btn_list'] = [
                            [
                                'type' => 1,
                                'title' => '取消连麦',
                                'target' => 'api',
                                'link' => '/live/v2/live/request_rtc_interaction?action=4&need_auth=2',
                                'mic_auth_deny' => null,
                                'action' => 4,
                            ],
                            [
                                'type' => 2,
                                'title' => '连线中…',
                                'target' => '',
                                'link' => '',
                                'mic_auth_deny' => null,
                                'action' => 0,
                            ]
                        ];
                    } else
                    {   // 连麦中
                        $popMsgRtc['user_info']['status'] = (int)($nowRtcData['network_status'] ?? 1);
                        $networkDesc = $rtcRecordModel->getRtcNetworkStatusDesc((int)($nowRtcData['live_network_status'] ?? 1), (int)($nowRtcData['user_network_status'] ?? 1));
                        $popMsgRtc['des_network'] = $networkDesc['live_network_desc'];

                        $popMsgRtc['btn_list'] = [
                            [
                                'type' => 1,
                                'title' => '挂断',
                                'target' => 'api',
                                'link' => '/live/v2/live/request_rtc_interaction?action=5&need_auth=2',
                                'mic_auth_deny' => null,
                                'action' => 2,
                            ]
                        ];

                        $rtcSwitch = 2;
                    }
                    $data['pop_msg_rtc'] = $popMsgRtc;
                } else
                {   // 判断有没有申请  有申请带 ...
                    // 获取当前申请连麦的所有用户
                    $allRequestRtcUserList = $rtcRecordModel->getRtcUserList($data['id']);
                    if ($allRequestRtcUserList)
                    {
                        $rtcSwitch = 3;
                    }
                }
            } else
            {
                $requestRtcId = (new LiveRtcRecord())->isRequestRtc($data['id'], $uid);
                if ($requestRtcId > 0)
                {
                    $rtcSwitch = 3;
                } else
                {
                    $rtcSwitch = (int)(Cache::get("live:rtc_switch:{$live_id}:{$data['id']}", 0));
                }

                if ($nowRtcData)
                {
                    $popMsgRtc = [
                        'type' => 1,
                        'toast' => '',
                        'user_info' => [
                            'name' => $nowRtcData['nickname'],
                            'avatar' => $nowRtcData['avatar'],
                            'uen' => $nowRtcData['uen'],
                            'status' => 0,
                            'des_network' => '',
                        ],
                        'btn_list' => []
                    ];
                    if ((int)$nowRtcData['uid'] === (int)$uid)
                    {   // 当前直播 被连麦用户
                        $popMsgRtc['user_info']['name'] = $anchor['name'];
                        $popMsgRtc['user_info']['avatar'] = $anchor['avatar'];
                        $nowRtcData['status'] = (int)$nowRtcData['status'];
                        if ($nowRtcData['status'] === 1)
                        {   // 等待接听
                            $popMsgRtc['btn_list'] = [
                                [
                                    'type' => 1,
                                    'title' => '接听',
                                    'target' => 'api',
                                    'link' => '/api/v29/rtc_interaction?action=1&need_auth=2',
                                    'mic_auth_deny' => [
                                        'target' => 'api',
                                        'link' => '/api/v29/rtc_interaction?action=2&need_auth=2',
                                    ],
                                    'action' => 1,
                                ], [
                                    'type' => 1,
                                    'title' => '拒绝',
                                    'target' => 'api',
                                    'link' => '/api/v29/rtc_interaction?action=2&need_auth=2',
                                    'mic_auth_deny' => null,
                                    'action' => 3,
                                ], [
                                    'type' => 2,
                                    'title' => '主播申请语音连麦',
                                    'target' => '',
                                    'link' => '',
                                    'mic_auth_deny' => null,
                                    'action' => 0,
                                ]
                            ];
                        } elseif ($nowRtcData['status'] === 2)
                        {   // 连线中
                            $popMsgRtc['btn_list'] = [
                                [
                                    'type' => 1,
                                    'title' => '挂断',
                                    'target' => 'api',
                                    'link' => '/api/v29/rtc_interaction?action=3&need_auth=2',
                                    'mic_auth_deny' => null,
                                    'action' => 2,
                                ],
                                [
                                    'type' => 2,
                                    'title' => '连线中…',
                                    'target' => '',
                                    'link' => '',
                                    'mic_auth_deny' => null,
                                    'action' => 0,
                                ]
                            ];
                        } else
                        {   // 连麦中
                            $popMsgRtc['user_info']['status'] = (int)($nowRtcData['network_status'] ?? 1);
                            $networkDesc = $rtcRecordModel->getRtcNetworkStatusDesc((int)($nowRtcData['live_network_status'] ?? 1), (int)($nowRtcData['user_network_status'] ?? 1));
                            $popMsgRtc['des_network'] = $networkDesc['user_network_desc'];
                            $rtcSwitch = 2;
                            $popMsgRtc['btn_list'] = [
                                [
                                    'type' => 1,
                                    'title' => '挂断',
                                    'target' => 'api',
                                    'link' => '/api/v29/rtc_interaction?action=3&need_auth=2',
                                    'mic_auth_deny' => null,
                                    'action' => 2,
                                ]
                            ];
                        }
                    } else
                    {   // 直播间 内 其他用户
                        if (in_array($nowRtcData['status'], [1, 2], false))
                        {   // 等待接听
                            $popMsgRtc['btn_list'] = [
                                [
                                    'type' => 2,
                                    'title' => '等待接听中…',
                                    'target' => '',
                                    'link' => '',
                                    'mic_auth_deny' => null,
                                    'action' => 0,
                                ]
                            ];
                        } else
                        {   // 连麦中
                            $popMsgRtc['user_info']['status'] = 1;     // 状态【0=》未连接状态；1=》连接成功了（在头像右下角，显示蓝色gif动图）；2=》网络异常（在头像右下角，显示黄色gif动图）；】
                        }
                    }
                    $data['pop_msg_rtc'] = $popMsgRtc;
                }
            }
            $data['rtc_status'] = $rtcSwitch;
        } else//直播结束
        {
            $data['status'] = 2;
        }
        if ($uid)
        {
            //是否踢出直播间
            $isGun = Cache::get('out_user-' . $live_id . '-' . $recordId . '-' . $uid);
            if ($isGun)
            {
                $data['status'] = 3;
            }
        }

        //获取解答互动信息
        $data['answer_btns'] = [];
        if ($isManage)
        {
            $data['answer_btns'][] = (new LiveAnswerAstroRecord())->getLiveManageAnswerProgressInfo($recordId, 1);
            $data['answer_btns'][] = (new LiveAnswerDiceRecord())->getLiveManageAnswerProgressInfo($recordId, 1);
            $data['answer_btns'][] = (new LiveAnswerTarotRecord())->getLiveManageAnswerProgressInfo($recordId, 1);
            $data['answer_btns'] = array_filter($data['answer_btns']);
        } else
        {
            if ($uid && $recordId)
            {
                $data['answer_btns'][] = (new LiveAnswerAstroRecord())->getUserAnswerProgressInfo($uid, $recordId, 1);
                $data['answer_btns'][] = (new LiveAnswerDiceRecord())->getUserAnswerProgressInfo($uid, $recordId, 1);
                $data['answer_btns'][] = (new LiveAnswerTarotRecord())->getUserAnswerProgressInfo($uid, $recordId, 1);
            }
        }

        return $data;
    }

    /**
     * 更新直播记录
     * @param $recordId
     * @param $data
     * @return false
     */
    public function updateData($recordId, $data)
    {
        try
        {
            $this->save($data, ['id' => $recordId]);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $recordId)->setCache($data);
            return true;
        }
        catch (\Exception $e)
        {
            return false;
        }
    }

    public function addLive($data)
    {
        try
        {
            $id = $this->insertGetId($data);

            $this->listDataAdd($data['live_id'], [$id => $id]);

            CacheManage::getInstance()->setCacheConfig('live.live_recording')
                ->setCacheType('string')
                ->setCacheKeyDetail('new_record_id', $data['live_id'])->setCache($id, 'new_record_id');

            CacheManage::getInstance()->setCacheConfig('live.live_recording')
                ->setCacheType('string')
                ->setCacheKeyDetail('new_record_id', 0)->rmCache('new_record_id');

            return $id;
        }
        catch (\Exception $e)
        {
            Log::write("开启直播失败：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
            return 0;
        }
    }

    /**
     * 获取当前直播间所有直播记录
     * @param $liveId
     * @return array|mixed
     * @throws \Exception
     */
    public function recordList($liveId)
    {
        $page = input('page/d', 1);
        $dataList = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $liveId)
            ->setSort('desc')
            ->setPage($page)
            ->getListPage(function ($ids = [], $isCache = true, $sortType = 'desc') use ($liveId)
            {
                return $this->getInfoByIdsInData($ids, [$liveId], $sortType);
            }, 'id', [], 0);
        $dataList['data'] = $this->resetRecordList($dataList['data']);
        return $dataList;
    }

    /**
     * 直播记录数据重组
     * @param $data
     */
    protected function resetRecordList($data)
    {
        $res = [];
        foreach ($data as $datum)
        {
            $res[] = [
                'id' => $datum['id'],
                'title' => $datum['title'],
                'time' => date('Y-m-d H:i:s', $datum['live_start_time']),
                'target' => 'local',
                'link' => ''//todo 直播记录详情h5
            ];
        }
        return $res;
    }


    /**
     * 获取当前直播间最新的直播记录
     * @param $liveId
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function getNewestRecord($liveId)
    {
        $config = (new AppConfig())->configInfo('live');

        $liveTestUser = explode(',', $config['live_test_user'] ?? '');

        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheType('string')
            ->setCacheKeyDetail('new_record_id', $liveId)
            ->getDataAndSet(function () use ($liveId, $liveTestUser)
            {
                try
                {
                    if ($liveId)
                    {
                        $res = $this->where(['live_id' => $liveId])->order('id', 'DESC')->field('id')->findOrFail();
                    } else
                    {
                        $res = $this->whereNotIn('live_id', $liveTestUser)->order('id', 'DESC')->field('id')->findOrFail();
                    }
                    return $res['id'];
                }
                catch (\Exception $e)
                {
                    return 0;
                }
            }, [], 'new_record_id');
        // 更新缓存操作示例
        // CacheManage::getInstance()->setCacheConfig($this->cacheModel)
        //     ->setCacheType('string')
        //     ->setCacheKeyDetail('new_record_id',$liveId)->setCache("3",'new_record_id');
        return $data ? (int)$data : 0;
    }


    /**
     * 批量获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('id', $ids);
            } else
            {
                $this->where(['live_id' => $type[0], 'status' => 2]);
            }

            $res = $this->order('id', 'DESC')
                ->column('*', 'id');
        }
        catch (\Exception $e)
        {
            Log::write('合盘结果获取异常：' . $e->getMessage(), 'error', true);
            return [];
        }

        return $res;
    }

    /**
     *  获取直播记录详情
     */
    public function getRecordDetail($liveId, $liveRecordId)
    {
        $recordInfo = $this->getInfoById($liveRecordId);

        if (empty($recordInfo) || $recordInfo['live_id'] != $liveId)
        {
            return null;
        }

        $hotData = (new LiveStatusDataRecord())->getLiveTotalData([$liveRecordId]);

        $userNum = Db::table('live_data.live_user_' . $liveId)->where(['live_record_id' => $liveRecordId])->group('uid')->count();

        $chartList = [
            [
                'proportion' => (float)($hotData['total_hot_sum'] > 0 ? sprintf("%.1f", $hotData['online_user_num_sum'] / $hotData['total_hot_sum'] * 100) : 0),
                'color' => '#1FCC86',
                'name' => '在线',
            ],
            [
                'proportion' => (float)($hotData['total_hot_sum'] > 0 ? sprintf("%.1f", $hotData['zan_hot_sum'] / $hotData['total_hot_sum'] * 100) : 0),
                'color' => '#FE5D5D',
                'name' => '点赞',
            ],
            [
                'proportion' => (float)($hotData['total_hot_sum'] > 0 ? sprintf("%.1f", $hotData['comment_hot_sum'] / $hotData['total_hot_sum'] * 100) : 0),
                'color' => '#6B58C8',
                'name' => '弹幕',
            ],
            [
                'proportion' => (float)($hotData['total_hot_sum'] > 0 ? sprintf("%.1f", $hotData['gift_hot_sum'] / $hotData['total_hot_sum'] * 100) : 0),
                'color' => '#FFC51B',
                'name' => '礼物',
            ]
        ];

        $commonList = [
            [
                'type' => 1,
                'title' => '数据详情',
                'desc' => ''
            ],
            [
                'type' => 2,
                'title' => '开播时间：',
                'desc' => date('Y-m-d H:i:s', $recordInfo['live_start_time'])
            ],
            [
                'type' => 2,
                'title' => '开播时长：',
                'desc' => $recordInfo['live_duration'] > 60 ? floor($recordInfo['live_duration'] / 60) . '小时' . ($recordInfo['live_duration'] % 60) . '分钟' : ($recordInfo['live_duration'] % 60) . '分钟'
            ],
            [
                'type' => 2,
                'title' => '累计观看人数：',
                'desc' => $userNum . '人'
            ],
            [
                'type' => 2,
                'title' => '平均同时在线人数：',
                'desc' => $hotData['online_user_num_avg'] . '人'
            ],
            [
                'type' => 2,
                'title' => '同时在线人数峰值：',
                'desc' => $hotData['online_user_num_max'] . '人'
            ],
            [
                'type' => 2,
                'title' => '热度峰值：',
                'desc' => $hotData['total_hot_max']
            ],
            [
                'type' => 2,
                'title' => '热度平均值：',
                'desc' => (int)$hotData['total_hot_avg']
            ],
            [
                'type' => 2,
                'title' => '弹幕总量：',
                'desc' => (int)$hotData['comment_num_sum']
            ],
            [
                'type' => 2,
                'title' => '点赞贡献热度值：',
                'desc' => (int)$hotData['zan_num_sum']
            ],
            [
                'type' => 2,
                'title' => '当日优惠券使用率：',
                'desc' => (new LiveCouponActiveGiveRecord())->getLiveRecordCouponUseRatio($liveRecordId, $recordInfo['live_start_time'] + $recordInfo['live_duration'])
            ],
        ];

        $liveOrderData = (new LiveOrderData())->getLiveRecordOrderData([$liveRecordId]);

        $commonTableListItem1 = [
            [
                'type' => 1,
                'type_1_data' => '平台商品销售'
            ],
            [
                'type' => 2,
                'type_2_data' => [
                    '价值总额',
                    '优惠',
                    '实际销售金额',
                ]
            ],
        ];

        if (isset($liveOrderData['goods']))
        {
            $commonTableListItem1[] = [
                'type' => 3,
                'type_3_data' => [
                    sprintf("%.2f", ($liveOrderData['goods_price']['price'] ?? 0) + ($liveOrderData['goods_price']['discount'] ?? 0)) . '元',
                    sprintf("%.2f", $liveOrderData['goods_price']['discount'] ?? 0) . '元',
                    sprintf("%.2f", $liveOrderData['goods_price']['price'] ?? 0) . '元',
                ]
            ];

            $desc = '';
            foreach ($liveOrderData['goods'] as $goodItem)
            {
                $desc .= "{$goodItem['name']}x{$goodItem['num']}、";
            }
            $desc = rtrim($desc, '、');
            $commonTableListItem1[] = [
                'type' => 4,
                'type_4_data' => [
                    'title' => '销售详情：',
                    'des' => $desc,
                ]
            ];
        } else
        {
            $commonTableListItem1[] = [
                'type' => 3,
                'type_3_data' => [
                    '0元',
                    '0元',
                    '0元',
                ]
            ];
            $commonTableListItem1[] = [
                'type' => 4,
                'type_4_data' => [
                    'title' => '销售详情：',
                    'des' => '',
                ]
            ];
        }

        $commonTableListItem2 = [
            [
                'type' => 1,
                'type_1_data' => '万幸商城销售'
            ],
            [
                'type' => 2,
                'type_2_data' => [
                    '价值总额',
                    '优惠',
                    '实际销售金额',
                ]
            ],
        ];

        if (isset($liveOrderData['mall_goods']))
        {
            $commonTableListItem2[] = [
                'type' => 3,
                'type_3_data' => [
                    sprintf("%.2f", ($liveOrderData['mall_goods_price']['price'] ?? 0) + ($liveOrderData['mall_goods_price']['discount'] ?? 0)) . '元',
                    sprintf("%.2f", $liveOrderData['mall_goods_price']['discount'] ?? 0) . '元',
                    sprintf("%.2f", $liveOrderData['mall_goods_price']['price'] ?? 0) . '元',
                ]
            ];

            $desc = '';
            foreach ($liveOrderData['mall_goods'] as $goodItem)
            {
                $desc .= "{$goodItem['name']}x{$goodItem['num']}、";
            }
            $desc = rtrim($desc, '、');
            $commonTableListItem2[] = [
                'type' => 4,
                'type_4_data' => [
                    'title' => '销售详情：',
                    'des' => $desc,
                ]
            ];
        } else
        {
            $commonTableListItem2[] = [
                'type' => 3,
                'type_3_data' => [
                    '0元',
                    '0元',
                    '0元',
                ]
            ];
            $commonTableListItem2[] = [
                'type' => 4,
                'type_4_data' => [
                    'title' => '销售详情：',
                    'des' => '',
                ]
            ];
        }


        //解答打赏收益
        $answerRewardData = (new LiveAnswerReward())->getAnswerReward([$liveRecordId]);
        $astroPriceData = (new LiveAnswerAstroRecord())->getAnswerEarningsData([$liveRecordId]);
        $dicePriceData = (new LiveAnswerDiceRecord())->getAnswerEarningsData([$liveRecordId]);
        $tarotPriceData = (new LiveAnswerTarotRecord())->getAnswerEarningsData([$liveRecordId]);

        $answerPrice = sprintf("%.2f", $astroPriceData['earnings'] + $dicePriceData['earnings'] + $tarotPriceData['earnings'] + ($answerRewardData['total_coin'] / 10));

        $commonAnswerTableSingleList = [
            [
                'type' => 3,
                'title' => '解答收益总额：',
                'desc' => $answerPrice . '元',
            ],
            [
                'type' => 1,
                'title' => '看盘解答收益：',
                'desc' => sprintf("%.2f元", $astroPriceData['earnings']),
                'tips' => ''
            ],
            [
                'type' => 2,
                'title' => '收益详情：',
                'desc' => $astroPriceData['desc'],
            ],
            [
                'type' => 1,
                'title' => '骰子解答收益：',
                'desc' => sprintf("%.2f元", $dicePriceData['earnings']),
                'tips' => ''
            ],
            [
                'type' => 2,
                'title' => '收益详情：',
                'desc' => $dicePriceData['desc'],
            ],
            [
                'type' => 1,
                'title' => '塔罗解答收益：',
                'desc' => sprintf("%.2f元", $tarotPriceData['earnings']),
                'tips' => ''
            ],
            [
                'type' => 2,
                'title' => '收益详情：',
                'desc' => $tarotPriceData['desc'],
            ],
            [
                'type' => 1,
                'title' => '解答打赏：',
                'desc' => $answerRewardData['total_coin'] . '准币',
                'tips' => ''
            ],
            [
                'type' => 2,
                'title' => '收益详情：',
                'desc' => $answerRewardData['reward_info_desc'],
            ],
            [//解答记录按钮（放到最后一个）
                'type' => 4,
                'title' => "解答记录",
                'desc' => "",
                'target' => 'local',
                'link' => 'liver_page?page=answer_list&live_record_id=' . $liveRecordId . '&type=1',
            ],
        ];

        $giftSendData = (new LiveGiftSendRecord())->getLiveRecordGiftData([$liveRecordId]);

        $commonGiftTableSingleList = [
            [
                'type' => 1,
                'title' => '礼物收益：',
                'desc' => $giftSendData['type2']['coin'] . '准币',
                'tips' => ''
            ],
            [
                'type' => 2,
                'title' => '礼物详情：',
                'desc' => $giftSendData['type2']['desc'],
            ],
            [
                'type' => 1,
                'title' => '背包礼物：',
                'desc' => $giftSendData['type3']['coin'] . '准币',
                'tips' => ''
            ],
            [
                'type' => 2,
                'title' => '礼物详情：',
                'desc' => $giftSendData['type3']['desc'],
            ],
            [
                'type' => 1,
                'title' => '免费礼物：',
                'desc' => '',
                'tips' => ''
            ],
            [
                'type' => 2,
                'title' => '礼物详情：',
                'desc' => $giftSendData['type1'],
            ]
        ];

        return [
            'chart_list' => $chartList,
            'common_list' => $commonList,
            'common_table_list' => [
                $commonTableListItem1,
                $commonTableListItem2
            ],
            'common_table_single_list' => [$commonAnswerTableSingleList, $commonGiftTableSingleList]
        ];
    }

    /**
     * @param $liveId
     * @param $startTime
     * @param $endTIme
     * @return array
     * @throws \think\Exception
     */
    public function getTimeRangeDetail($liveId, $startTime, $endTIme)
    {
        $liveRecordIds = $this->where(['live_id' => $liveId, 'status' => 2])->where('live_start_time', 'between time', [$startTime, $endTIme])->column('id');

        $timeLength = $this->whereIn('id', $liveRecordIds)->sum('live_duration');

        $hotData = (new LiveStatusDataRecord())->getLiveTotalData($liveRecordIds);

        $commonList = [
            [
                'type' => 1,
                'title' => '数据详情',
                'desc' => ''
            ],
            [
                'type' => 2,
                'title' => '直播时长：',
                'desc' => $timeLength > 60 ? floor($timeLength / 60) . '小时' . ($timeLength % 60) . '分钟' : ($timeLength % 60) . '分钟'
            ],
            [
                'type' => 2,
                'title' => '累计观看人数：',
                'desc' => (Db::table('live_data.live_user_' . $liveId)->whereIn('live_record_id', $liveRecordIds)->group('uid')->count()) . '人',
            ],
            [
                'type' => 2,
                'title' => '每日在线观看人数平均值：',
                'desc' => ceil($hotData['online_user_num_avg']) . '人'
            ],
            [
                'type' => 2,
                'title' => '每日热度平均值：',
                'desc' => ceil($hotData['total_hot_avg'])
            ],
            [
                'type' => 2,
                'title' => '弹幕总量：',
                'desc' => (int)$hotData['comment_num_sum']
            ],
        ];

        $liveOrderData = (new LiveOrderData())->getLiveRecordOrderData($liveRecordIds);

        $commonTableListItem1 = [
            [
                'type' => 1,
                'type_1_data' => '平台商品销售'
            ],
            [
                'type' => 2,
                'type_2_data' => [
                    '价值总额',
                    '优惠',
                    '实际销售金额',
                ]
            ],
        ];

        if (isset($liveOrderData['goods']))
        {
            $commonTableListItem1[] = [
                'type' => 3,
                'type_3_data' => [
                    sprintf("%.2f", ($liveOrderData['goods_price']['price'] ?? 0) + ($liveOrderData['goods_price']['discount'] ?? 0)) . '元',
                    sprintf("%.2f", $liveOrderData['goods_price']['discount'] ?? 0) . '元',
                    sprintf("%.2f", $liveOrderData['goods_price']['price'] ?? 0) . '元',
                ]
            ];

            $desc = '';
            foreach ($liveOrderData['goods'] as $goodItem)
            {
                $desc .= "{$goodItem['name']}x{$goodItem['num']}、";
            }
            $desc = rtrim($desc, '、');
            $commonTableListItem1[] = [
                'type' => 4,
                'type_4_data' => [
                    'title' => '销售详情：',
                    'des' => $desc,
                ]
            ];
        } else
        {
            $commonTableListItem1[] = [
                'type' => 3,
                'type_3_data' => [
                    '0元',
                    '0元',
                    '0元',
                ]
            ];
            $commonTableListItem1[] = [
                'type' => 4,
                'type_4_data' => [
                    'title' => '销售详情：',
                    'des' => '你是输了几次，但你还会东山再起的',
                ]
            ];
        }

        $commonTableListItem2 = [
            [
                'type' => 1,
                'type_1_data' => '万幸商城销售'
            ],
            [
                'type' => 2,
                'type_2_data' => [
                    '价值总额',
                    '优惠',
                    '实际销售金额',
                ]
            ],
        ];

        if (isset($liveOrderData['mall_goods']))
        {
            $commonTableListItem2[] = [
                'type' => 3,
                'type_3_data' => [
                    sprintf("%.2f", ($liveOrderData['mall_goods_price']['price'] ?? 0) + ($liveOrderData['mall_goods_price']['discount'] ?? 0)) . '元',
                    sprintf("%.2f", $liveOrderData['mall_goods_price']['discount'] ?? 0) . '元',
                    sprintf("%.2f", $liveOrderData['mall_goods_price']['price'] ?? 0) . '元',
                ]
            ];

            $desc = '';
            foreach ($liveOrderData['mall_goods'] as $goodItem)
            {
                $desc .= "{$goodItem['name']}x{$goodItem['num']}、";
            }
            $desc = rtrim($desc, '、');
            $commonTableListItem2[] = [
                'type' => 4,
                'type_4_data' => [
                    'title' => '销售详情：',
                    'des' => $desc,
                ]
            ];
        } else
        {
            $commonTableListItem2[] = [
                'type' => 3,
                'type_3_data' => [
                    '0元',
                    '0元',
                    '0元',
                ]
            ];
            $commonTableListItem2[] = [
                'type' => 4,
                'type_4_data' => [
                    'title' => '销售详情：',
                    'des' => '你是输了几次，但你还会东山再起的',
                ]
            ];
        }

        //解答打赏收益
        $answerRewardData = (new LiveAnswerReward())->getAnswerReward($liveRecordIds);
        $astroPriceData = (new LiveAnswerAstroRecord())->getAnswerEarningsData($liveRecordIds);
        $dicePriceData = (new LiveAnswerDiceRecord())->getAnswerEarningsData($liveRecordIds);
        $tarotPriceData = (new LiveAnswerTarotRecord())->getAnswerEarningsData($liveRecordIds);

        $answerPrice = sprintf("%.2f", $astroPriceData['earnings'] + $dicePriceData['earnings'] + $tarotPriceData['earnings'] + ($answerRewardData['total_coin'] / 10));
        $commonAnswerTableSingleList = [
            [
                'type' => 3,
                'title' => '解答收益总额：',
                'desc' => $answerPrice . '元',
            ],
            [
                'type' => 1,
                'title' => '看盘解答收益：',
                'desc' => sprintf("%.2f元", $astroPriceData['earnings']),
            ],
            [
                'type' => 1,
                'title' => '骰子解答收益：',
                'desc' => sprintf("%.2f元", $dicePriceData['earnings']),
            ],
            [
                'type' => 1,
                'title' => '塔罗解答收益：',
                'desc' => sprintf("%.2f元", $tarotPriceData['earnings']),
            ],
            [
                'type' => 1,
                'title' => '解答打赏：',
                'desc' => $answerRewardData['total_coin'] . '准币',
            ],
        ];

        //礼物收益
        $giftSendData = (new LiveGiftSendRecord())->getLiveRecordGiftData($liveRecordIds);

        $commonGiftTableSingleList = [
            [
                'type' => 3,
                'title' => '礼物实际收益总额：',
                'desc' => $giftSendData['type2']['coin'] - $giftSendData['type3']['coin'] . '准币'
            ],
            [
                'type' => 1,
                'title' => '礼物收益：',
                'desc' => $giftSendData['type2']['coin'] . '准币',
            ],
            [
                'type' => 2,
                'title' => '礼物详情',
                'desc' => $giftSendData['type2']['desc'],
            ],

            [
                'type' => 1,
                'title' => '背包礼物：',
                'desc' => $giftSendData['type3']['coin'] . '准币',
            ],
            [
                'type' => 2,
                'title' => '礼物详情：',
                'desc' => $giftSendData['type3']['desc'],
            ],
            [
                'type' => 1,
                'title' => '免费礼物：',
                'desc' => '',
            ],
            [
                'type' => 2,
                'title' => '礼物详情',
                'desc' => $giftSendData['type1'],
            ]
        ];

        return [
            'common_list' => $commonList,
            'common_table_list' => [
                $commonTableListItem1,
                $commonTableListItem2
            ],
            'common_table_single_list' => [$commonAnswerTableSingleList, $commonGiftTableSingleList]
        ];
    }

    /**
     * 检验直播记录
     * @param $liveId
     * @param $liveRecordId
     * @throws \Exception
     */
    public function checkRecordId(&$liveId, $liveRecordId)
    {
        $newId = $this->getNewestRecord($liveId);
        if (!empty($liveId) && ($liveRecordId < 1 || $liveRecordId > $newId))
        {
            Log::write("直播记录ID参数异常:直播间ID-{$liveId},最新的记录ID-{$newId},参数记录ID-$liveRecordId", 'error', true);
        } else
        {
            $record = $this->getInfoById($liveRecordId);
            $liveId = $record['live_id'] ?? $liveId;
        }
    }
}
